//
//  Exporter.m
//  iBioCAD
//
//  Created by Orbitus on 10/10/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "Exporter.h"


@implementation Exporter
- (void) awakeFromNib
{	
	entities = [managedObjectModel entitiesByName];
	dnaEntity = [entities valueForKey:@"DNA"];
	
	dnaSortTitle = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
	dnaSortDescriptors = [NSArray arrayWithObject: dnaSortTitle];
	dnaFetch = [[NSFetchRequest alloc] init];
	[dnaFetch setEntity: dnaEntity];
	[dnaFetch setSortDescriptors: dnaSortDescriptors];
	
}	
- (void) setController:(id)controller
{
	dnaArray = controller;
}
- (IBAction)export:(id)sender
{
	NSLog(@"Exporting....");
	
	myDocController = [NSDocumentController sharedDocumentController];
	myDocs = [myDocController documents];
	
	if ([myDocs count] == 0)
	{
		[myDocController openUntitledDocumentAndDisplay:YES error:nil];
	}
	id highlightDocument = [myDocController currentDocument];
	managedObjectContext = [highlightDocument managedObjectContext];
	managedObjectModel = [highlightDocument managedObjectModel];
	
	
	if ( [[exportName stringValue] isEqualToString:@""])
	{
		[exportName setStringValue:@"Untitled"];
	}
	[dnaFetch setEntity: dnaEntity];
	[dnaFetch setSortDescriptors: dnaSortDescriptors];	
	
	//Every sequence that is true for export will be added to an array
	//Perform Sequences fetch with custom predicate for export status
	predicate = [NSPredicate predicateWithFormat:@"export == 1"];
	//[dnaFetch setPredicate:predicate];
	NSString* chosinFormat = @"";
	switch ([[exportFormat selectedItem] tag]) {
		case 0:
			chosinFormat = @"acedb";
			break;
		case 1:
			chosinFormat = @"asn1";
			break;
		case 2:
			chosinFormat = @"aln";
			break;
		case 3:
			chosinFormat = @"codata";
			break;
		case 4:
			chosinFormat = @"debug";
			break;
		case 5:
			chosinFormat = @"embl";
			break;
		case 6:
			chosinFormat = @"fasta";
			break;
		case 7:
			chosinFormat = @"fitch";
			break;
		case 8:
			chosinFormat = @"gcg";
			break;
		case 9:
			chosinFormat = @"gcg8";
			break;
		case 10:
			chosinFormat = @"genbank";
			break;
		case 11:
			chosinFormat = @"hennig86";
			break;
		case 12:
			chosinFormat = @"ig";
			break;
		case 13:
			chosinFormat = @"jackknifer";
			break;
		case 14:
			chosinFormat = @"jackknifernon";
			break;
		case 15:
			chosinFormat = @"mega";
			break;
		case 16:
			chosinFormat = @"meganon";
			break;
		case 17:
			chosinFormat = @"msf";
			break;
		case 18:
			chosinFormat = @"pir";
			break;
		case 19:
			chosinFormat = @"ncbi";
			break;
		case 20:
			chosinFormat = @"nexus";
			break;
		case 21:
			chosinFormat = @"nexusnon";
			break;
		case 22:
			chosinFormat = @"pearson";
			break;
		case 23:
			chosinFormat = @"phylip";
			break;
		case 24:
			chosinFormat = @"phylip3";
			break;
		case 25:
			chosinFormat = @"staden";
			break;
		case 26:
			chosinFormat = @"strider";
			break;
		case 27:
			chosinFormat = @"swiss";
			break;
		case 28:
			chosinFormat = @"text";
			break;
		case 29:
			chosinFormat = @"treecon";
			break;
		default:
			break;
	}
	
	NSArray * dnaExportList = [[dnaArrayController arrangedObjects] filteredArrayUsingPredicate:predicate];
	
	//NSLog(@"MOC= %@",[managedObjectContext description]);
	//NSLog(@"DNA EXport List= %@",[dnaExportList description]);
	
	//take that array and spit each name/sequence as a large fasta file
	//Output this file onto the friendly iBioCAD desktop

	NSString* myDesktopFolderPath	=  [[[[NSBundle mainBundle] bundlePath] 
										 stringByDeletingLastPathComponent]
										stringByAppendingString:@"/Sequences/iBioCAD/Desktop/"];
	NSString* myOutFilePath = [[myDesktopFolderPath stringByAppendingPathComponent:[exportName stringValue]] stringByAppendingString:[NSString stringWithFormat:@".%@",chosinFormat]];
	
	int i;
	
	id myString = @"";
	int tempCount;
	int fileDivision = 1000;
	
	int ii=0,jj=0;
	/*
	int tempNum = [dnaExportList count];
	tempNum % 1000;
	*/
	if ([dnaExportList count] > fileDivision)
	{
		tempCount = fileDivision;
	}
	else
	{
		tempCount = [dnaExportList count];
	}
	for (i=0; i < tempCount; i++)
	{
		//THere is no new line at the end of name because name has a newline already...I don't want 2
		myString = [myString stringByAppendingString:[[dnaExportList objectAtIndex:i] valueForKey:@"title"] ];
		myString = [myString stringByAppendingString:[[[dnaExportList objectAtIndex:i] valueForKey:@"sequence"]stringByAppendingString:@"\n"] ];
	}
	//NSLog(@"your String=%@",myString);
	[myString writeToFile:myOutFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
	//convert that file to the desired format
	//NSTask with seqret
	NSString* seqretPath	= @"/UnixApps/EMBOSS/emboss/seqret";

	
	exportPathString = [[exportPath URL] path];
	
	NSTask *seqret = [[NSTask alloc] init];
	NSPipe *pipe = [[NSPipe alloc] init];
	NSFileHandle *handle;
	[seqret	setLaunchPath:seqretPath];
	[seqret setCurrentDirectoryPath:[[[[NSBundle mainBundle] bundlePath] 
									  stringByDeletingLastPathComponent]
									 stringByAppendingString:@"/Sequences/iBioCAD/Desktop/"]];
	NSMutableArray* seqretArguments = [[NSMutableArray alloc]	init];
	[seqretArguments addObject:@"-sequence"];
	[seqretArguments addObject:myOutFilePath];
	if ([exportOption state] == 1){
		[seqretArguments addObject:@"-ossingle"];	
	} 
	[seqretArguments addObject:@"-osf"];
	[seqretArguments addObject:chosinFormat];
	[seqretArguments addObject:@"-outseq"];
	[seqretArguments addObject:[exportPathString stringByAppendingString:[[exportName stringValue] stringByAppendingPathExtension:chosinFormat]]];
	[seqretArguments addObject:@"-auto"];	
	[seqret setArguments:seqretArguments];
	
	[seqret setStandardOutput:pipe];
	[seqret launch];
	[seqret terminate];
	[seqret release];
	seqret = nil;
	//during which we spit to either the seqretsplit or seqret OR use -ossingle option
}
@end
